from fastapi import APIRouter, Depends
import db.version_update_crud as dbutils
from db.database import SessionLocal, get_db
from sqlalchemy.orm import Session
from domain.response import success, error
from utils.utils import Version2UpdateVOWrapper
from service.whitelist import id_in_whitelist
from pybloom_live import BloomFilter
from constant.whiteList import get_white_list

from db import models
from typing import Optional

router = APIRouter(
    prefix="/versionUpdate",
    tags=["versionUpdate"],
    dependencies=[],
    responses={404: {"description": "VersionConfig error"}}
)


@router.get("/checkUpdate")
async def check_update(
        version: str,  # 版本
        device_platform: str,  # 平台(android/ios)
        device_id: str,  # 设备id
        os_api: int,  # 系统版本【安卓系统下】
        channel: str,  # 不同应用商店
        aid: str,  # app的唯一标识
        cpu_arch: str,  # CPU架构
        db: Session = Depends(get_db),  # 数据库持有对象
):
    # 白名单判断
    if not await id_in_whitelist(version, device_id):
        return await error(41003, "不在白名单内")

    # 除白名单以外的判断
    rule = await dbutils.get_update_rule(
        db,
        version=version,
        device_platform=device_platform,
        os_api=os_api,
        channel=channel,
        aid=aid,
        cpu_arch=cpu_arch,
    )
    if isinstance(rule, models.Version):
        resultVO = await Version2UpdateVOWrapper(rule)
        return await success(resultVO)
    return await error(41002, "无可用更新")


# 客户端可命中测试数据
tcm0 = \
    {
        "version": "14",
        "device_platform": "Android",
        "device_id": "gkgPR89zwtpvpGAZ",
        "os_api": 15,
        "channel": "GooglePlay",
        "version_code": "14.01.01.10",
        "update_version_code": "14.01.01.10",
        "aid": 23,
        "cpu_arch": "x64"
    }


@router.get("/downloadCount")
async def download_count(bid: str, db: Session = Depends(get_db)):
    rule = db.query(models.Version).filter(models.Version.bid == bid).first()
    # print(">:before")
    # print(rule.install_count)
    if rule:
        setattr(rule, 'install_count', rule.install_count + 1)
        db.commit()
        db.flush()
        db.refresh(rule)
        # print(rule.install_count)
        return await success(data="bid:{0} install_count+1".format(bid))

    return await error(41001, msg="没有此bid:{0}".format(bid))

# 测试bid: V1455900450258821120
